package cn.zhengwenzhou.system.service.impl;

import cn.zhengwenzhou.system.common.Constant;
import cn.zhengwenzhou.system.dao.UserDao;
import cn.zhengwenzhou.system.entity.User;
import cn.zhengwenzhou.system.service.UserService;
import cn.zhengwenzhou.system.utils.CookieUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wen
 * @version 1.0
 * @date 2017/07/29 23:58
 * @description 用户Service实现
 */
@Service
public class UserServiceImpl implements UserService
{
	@Resource
	private UserDao userDaoImpl;
	
	@Override
	public List<User> getAll()
	{
		return userDaoImpl.getAll();
	}
	
	@Override
	public List<User> getListByPage(int pageIndex, int pageSize)
	{
		Map<String, Integer> params = new HashMap<>();
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);
		return userDaoImpl.getListByPage(params);
	}
	
	@Override
	public User getUserById(long id)
	{
		List<User> users = userDaoImpl.getUserById(id);
		User user = null;
		if(users.size() > 0)
		{
			user = users.get(0);
		}
		return user;
	}
	
	@Override
	public User getUserByUsername(String username)
	{
		List<User> users = userDaoImpl.getUserByUsername(username);
		User user = null;
		if(users.size() > 0)
		{
			user = users.get(0);
		}
		return user;
	}
	
	@Override
	public boolean exist(String username)
	{
		return userDaoImpl.exist(username)==0?false:true;
	}
	
	@Override
	public int count()
	{
		return userDaoImpl.count();
	}
	
	@Override
	public void insert(User user)
	{
		userDaoImpl.insert(user);
	}
	
	@Override
	public void update(User user)
	{
		userDaoImpl.update(user);
	}
	
	@Override
	public void trueDelete(long id)
	{
		userDaoImpl.trueDelete(id);
	}
	
	@Override
	public void delete(long id)
	{
		userDaoImpl.delete(id);
	}
	
	@Override
	public void batchDelete(List<Long> ids)
	{
		userDaoImpl.batchDelete(ids);
	}
	
	@Override
	public long getUserIdFromCookie(HttpServletRequest request)
	{
		return Long.parseLong(this.getLoggerCookie(request, "userId"));
	}
	
	@Override
	public String getUsernameFromCookie(HttpServletRequest request)
	{
		return this.getLoggerCookie(request, "username");
	}
	
	@Override
	public User getSessionUser(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Constant.SESSION_USER);
		return user;
	}
	
	private String getLoggerCookie(HttpServletRequest request, String field) {
		String cookie = CookieUtils.getCookieValue(CookieUtils.LOGGER_COOKIE, request);
		if("id".equals(field)) {
			return cookie.split(";")[0];
		}
		return cookie.split(";")[1];
	}
	
}
